<template>
  <div class="inner-container">
    <div title="点击更换头像">
      <el-upload class="avatar-uploader" :action="uploadUrl" :headers="tokenHeaders"
                 :show-file-list="false" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
        <img v-if="formData.avatar" :src="formData.avatar" class="avatar" alt=""/>
        <el-icon v-else class="avatar-uploader-icon"><Plus/></el-icon>
      </el-upload>
    </div>
    <br><br>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
      <el-form-item label="账号">
        <span v-text="formData.username"></span>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入昵称"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱"/>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机"/>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="formData.sex">
          <el-radio :value="0">男</el-radio>
          <el-radio :value="1">女</el-radio>
          <el-radio :value="2">未知</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">修改</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {ElMessage} from 'element-plus'
import store from '@/store'
import request from '@/utils/request'
import {getToken} from '@/utils/auth'

// 更换头像 --------------------------------------------------

const uploadUrl = ref(process.env.VUE_APP_BASE_API + '/api/uploadImage')
const tokenHeaders = ref({token: getToken()})

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type.indexOf('image/') === -1) {
    ElMessage.error('请选择图片文件')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传图片大小不能超过2MB')
    return false
  }
  return true
}

const handleAvatarSuccess = (response) => {
  let avatarUrl = response.data
  request.patch('/api/sys/users/profile/avatar', {
    avatar: avatarUrl
  }).then(res => {
    formData.value.avatar = avatarUrl
    store.commit('setAvatar', avatarUrl)
    ElMessage.success('更换头像成功')
  })
}

// 个人资料 --------------------------------------------------

const formRef = ref()
const formData = ref({
  nickname: undefined,
  email: undefined,
  phone: undefined,
  sex: 0,
  avatar: undefined
})
const formRules = ref({
  nickname: [
    {required: true, message: '昵称为必填项'},
    {min: 2, max: 30, message: '长度在 2 到 30 个字符'}
  ],
  email: [
    {required: true, message: '邮箱为必填项'},
    {pattern: /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/, message: "邮箱格式无效"}
  ],
  phone: [
    {required: true, message: '手机为必填项'},
    {pattern: /^1[3-9]\d{9}$/, message: "手机格式无效"}
  ],
  sex: [
    {required: true, message: '性别为必选项'}
  ]
})

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      ElMessage.error('请正确填写参数')
      return
    }
    request.patch('/api/sys/users/profile', formData.value)
        .then(res => {
          store.commit('setNick', formData.value.nickname)
          ElMessage.success('修改成功')
        })
  })
}

const handleReset = () => {
  formRef.value.resetFields()
  getProfile()
}

const getProfile = () => {
  request.get('/api/sys/users/profile')
      .then(res => {
        formData.value = res.data
      })
}

onMounted(() => {
  getProfile()
})
</script>

<style scoped>
.avatar-uploader {
  width: 128px;
  height: 128px;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader .avatar {
  width: 128px;
  height: 128px;
  display: block;
}

.el-icon.avatar-uploader-icon {
  width: 128px;
  height: 128px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
